import {request} from '@/utils/request'
import type {PageQuery, PageResult} from '@/types/common'

// 表查询参数类型
export interface TableQuery {
    datasourceId?: string
    tableName?: string
}

// 代码生成相关接口
export interface CodegenServiceDTO {
    serviceName: string
    serviceDescription: string
    packageName: string
    generatePath: string
    author: string
    includeApi: boolean
    includeSwagger: boolean
    includeFeign: boolean
}

export interface CodegenTableDTO {
    id: string
    datasourceId: string
    tableName: string
    tableComment: string
    entityName: string
    packageName: string
    generatePath: string
    author: string
    columnsConfig: string
    columns: CodegenColumnDTO[]
    generateController: boolean
    generateService: boolean
    generateMapper: boolean
    generateXml: boolean
}

export interface CodegenColumnDTO {
    columnName: string
    columnType: string
    columnLength: number
    columnScale: number  // 字段精度，与后端保持一致
    isNullable: boolean
    columnComment: string
    defaultValue: string
    isPrimaryKey: boolean
    isAutoIncrement: boolean
    javaFieldType: string  // Java字段类型，与后端保持一致
    javaFieldName: string  // Java字段名，与后端保持一致
    showInList: boolean
    showInForm: boolean
    showInQuery: boolean
    queryType: string
    formType: string
    // 新增字段：支持ON UPDATE CURRENT_TIMESTAMP等特殊属性
    onUpdateCurrentTimestamp: boolean  // 是否在更新时自动更新为当前时间
    extra: string  // 额外的列属性，如 'on update CURRENT_TIMESTAMP'
}

export interface DatasourceDTO {
    id?: string
    name: string
    dbType: string
    driverClassName: string
    url: string
    username: string
    password: string
    databaseName?: string
    status: number
    remark?: string
}

export interface TableInfo {
    tableName: string
    tableComment: string
    tableType: string
}

export interface ColumnInfo {
    columnName: string
    columnType: string
    columnLength: number
    columnScale: number  // 字段精度，与后端保持一致
    isNullable: boolean
    columnComment: string
    defaultValue: string
    isPrimaryKey: boolean
    isAutoIncrement: boolean
    javaFieldType: string  // Java字段类型，与后端保持一致
    javaFieldName: string  // Java字段名，与后端保持一致
}

// 代码生成API
export const codegenApi = {
    // 生成微服务代码
    generateService: (data: CodegenServiceDTO): Promise<string> => {
        return request.post('/big-codegen/service', data)
    },

    // 下载微服务代码
    downloadService: (data: CodegenServiceDTO): Promise<Blob> => {
        return request.post('/big-codegen/service/download', data, {
            responseType: 'blob'
        })
    },

    // 生成表代码
    generateTable: (data: CodegenTableDTO): Promise<string> => {
        return request.post('/big-codegen/table', data)
    },

    // 下载表代码
    downloadTable: (data: CodegenTableDTO): Promise<Blob> => {
        return request.post('/big-codegen/table/download', data, {
            responseType: 'blob'
        })
    },

    // 同步表结构
    syncTable: async (datasourceId: string, tableName: string): Promise<void> => {
        await request.post(`/big-codegen/sync/table/${datasourceId}/${tableName}`)
    },

    // 同步代码
    syncCode: async (data: CodegenTableDTO): Promise<void> => {
        await request.post('/big-codegen/sync/code', data)
    },

    // 获取数据库表列表
    getTables: (datasourceId: string): Promise<TableInfo[]> => {
        return request.get(`/big-codegen/table/list/${datasourceId}`)
    },

    // 获取表字段信息
    getColumns: (datasourceId: string, tableName: string): Promise<ColumnInfo[]> => {
        return request.get(`/big-codegen/columns/${datasourceId}/${tableName}`)
    },

    // 生成实体类代码
    generateEntity: (data: CodegenTableDTO): Promise<string> => {
        return request.post('/big-codegen/table/generate/entity', data)
    },

    // 生成SQL代码
    generateSql: (data: CodegenTableDTO): Promise<string> => {
        return request.post('/big-codegen/table/generate/sql', data)
    },

    // 生成Mapper代码
    generateMapper: (data: CodegenTableDTO): Promise<string> => {
        return request.post('/big-codegen/table/generate/mapper', data)
    },

    // 生成Service代码
    generateServiceCode: (data: CodegenTableDTO): Promise<string> => {
        return request.post('/big-codegen/table/generate/service', data)
    },

    // 生成Controller代码
    generateController: (data: CodegenTableDTO): Promise<string> => {
        return request.post('/big-codegen/table/generate/controller', data)
    },

    // 生成DTO代码
    generateDTO: (data: CodegenTableDTO): Promise<string> => {
        return request.post('/big-codegen/table/generate/dto', data)
    },

    // 生成ServiceImpl代码
    generateServiceImpl: (data: CodegenTableDTO): Promise<string> => {
        return request.post('/big-codegen/table/generate/serviceImpl', data)
    },

    // 同步表结构
    syncTableStructure: (datasourceId: string, tableId: string): Promise<ColumnInfo[]> => {
        return request.post(`/big-codegen/table/sync/structure/${datasourceId}/${tableId}`)
    },

    // 保存表配置到数据库
    saveTableConfig: (data: CodegenTableDTO): Promise<number> => {
        return request.post('/big-codegen/table-config', data)
    },

    // 获取已保存的表配置列表
    getTableConfigs: (datasourceId?: string): Promise<CodegenTableDTO[]> => {
        return request.get('/big-codegen/table-config', {
            params: {datasourceId}
        })
    },

    // 分页查询表配置
    pageTableConfigs: (pageQuery: PageQuery<TableQuery>): Promise<PageResult<CodegenTableDTO>> => {
        return request.post('/big-codegen/table-config/page', pageQuery)
    },

    // 根据ID获取表配置
    getTableConfig: (id: string): Promise<CodegenTableDTO> => {
        return request.get(`/big-codegen/table-config/${id}`)
    },

    // 更新表配置
    updateTableConfig: async (id: string, data: CodegenTableDTO): Promise<void> => {
        await request.put(`/big-codegen/table-config/${id}`, data)
    },

    // 删除表配置
    deleteTableConfig: async (id: string): Promise<void> => {
        await request.delete(`/big-codegen/table-config/${id}`)
    },

    // 批量删除表配置
    batchDeleteTableConfigs: async (ids: string[]): Promise<void> => {
        await request.delete('/big-codegen/table-config/batch', {data: {ids}})
    },

    // 根据数据源和表名获取表配置
    getTableConfigByDatasourceAndTable: (datasourceId: string, tableName: string): Promise<CodegenTableDTO> => {
        return request.get(`/big-codegen/table-config/datasource/${datasourceId}/table/${tableName}`)
    },

    // 根据表名获取表配置
    getTableConfigByTableName: (tableName: string): Promise<CodegenTableDTO> => {
        return request.get(`/big-codegen/table-config/table/${tableName}`)
    },

    // 从数据库导入表配置
    importTableFromDatabase: (datasourceId: string, tableName: string): Promise<string> => {
        return request.post(`/big-codegen/table-config/import/${datasourceId}/${tableName}`)
    },

    // 创建表
    createTable: async (data: CodegenTableDTO): Promise<void> => {
        await request.post('/big-codegen/table/create', data)
    },

    // 生成代码
    generateCode: (data: CodegenTableDTO): Promise<Blob> => {
        return request.post('/big-codegen/table/generate', data, {responseType: 'blob'})
    },

}


// 表配置API
export const tableConfigApi = {
    // 根据ID获取表配置
    getTableConfig: (id: string): Promise<CodegenTableDTO> => {
        return request.get(`/big-codegen/table-config/${id}`)
    },

    // 根据表名获取表配置
    getTableConfigByTableName: (tableName: string): Promise<CodegenTableDTO> => {
        return request.get(`/big-codegen/table-config/table/${tableName}`)
    },

    // 根据数据源和表名获取表配置
    getTableConfigByDatasourceAndTable: (datasourceId: string, tableName: string): Promise<CodegenTableDTO> => {
        return request.get(`/big-codegen/table-config/datasource/${datasourceId}/table/${tableName}`)
    }
}

// 获取通用字段
export const getCommonFields = (): Promise<any[]> => {
    return request.get('/big-codegen/table-config/common/fields')
}

// 数据源查询参数类型
export interface DatasourceQuery {
    name?: string
    dbType?: string
}

// 数据源管理API
export const datasourceApi = {
    // 分页查询数据源
    page: (pageQuery: PageQuery<DatasourceQuery>): Promise<PageResult<DatasourceDTO>> => {
        return request.post('/big-codegen/datasource/page', pageQuery)
    },

    // 获取所有数据源
    list: (): Promise<DatasourceDTO[]> => {
        return request.post('/big-codegen/datasource/list',{})
    },

    // 根据ID获取数据源
    getById: (id: string): Promise<DatasourceDTO> => {
        return request.get(`/big-codegen/datasource/${id}`)
    },

    // 创建数据源
    create: async (data: DatasourceDTO): Promise<void> => {
        await request.post('/big-codegen/datasource', data)
    },

    // 更新数据源
    update: async ( data: DatasourceDTO): Promise<void> => {
        await request.put(`/big-codegen/datasource`, data)
    },

    // 删除数据源
    delete: async (id: string): Promise<void> => {
        await request.delete(`/big-codegen/datasource/${id}`)
    },

    // 测试连接
    testConnection: (data: DatasourceDTO): Promise<string> => {
        return request.post('/big-codegen/datasource/testConnection', data)
    }
}